package design_patterns_and_best_practices_in_java;

interface Iterator {
    public Object next();

    public boolean hasNext();
}

interface Aggregate {
    public Iterator createIterator();
}

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-11-14 下午1:48
 */
public class Chapter3Interator {
    public static void main(String[] args) {
        String[] arr = {"a", "b", "c", "d", "e", "f"};
        StringArray stringArray = new StringArray(arr);
        for (Iterator it = stringArray.createIterator(); it.hasNext(); ) {
            System.out.println(it.next());
        }
    }
}

class StringArray implements Aggregate {
    private String values[];

    public StringArray(String[] values) {
        this.values = values;
    }

    @Override
    public Iterator createIterator() {
        return new StringArrayInterator();
    }

    private class StringArrayInterator implements Iterator {
        private int position;

        @Override
        public Object next() {
            if (this.hasNext()) {
                return values[position++];
            }
            return null;
        }

        @Override
        public boolean hasNext() {
            return position < values.length;
        }
    }
}